import { _decorator, UITransform } from 'cc';
import { DIRECTION_ENUM, ENTITY_STATE_ENUM, ENTITY_TYPE_ENUM, EVENT_ENUM, SHAKE_DIRECTION_ENUM } from '../../Enums';
import EventManager from '../../Runtime/EventManager';
import { EntityManager } from '../../Base/EntityManager';
import DataManager from '../../Runtime/DataManager';
import { IEntity } from '../../Levels';
import { BurstStateMachine } from './BurstStateMachine';
import { TILE_WIDTH, TILE_HEIGHT } from '../Tile/TileManager';
const { ccclass, property } = _decorator;



@ccclass('BurstManager')
export class BurstManager extends EntityManager {
    async init(params: IEntity) {
        this.fsm = this.addComponent(BurstStateMachine)
        await this.fsm.init()
        super.init(params)

        const transform = this.getComponent(UITransform);
        transform.setContentSize(TILE_WIDTH, TILE_HEIGHT);

        //监听敌人攻击
        EventManager.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onBurst, this)

    }

    onDestroy() {
        super.onDestroy()
        EventManager.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onBurst)
    }

    update() {
        this.node.setPosition(this.x * TILE_WIDTH, -this.y * TILE_HEIGHT)
    }


    /**地块碎裂 */
    onBurst() {
        if (this.state === ENTITY_STATE_ENUM.DEATH || !DataManager.Instance.player) {
            return;
        }
        //拿到player的坐标
        const { x: playerX, y: playerY } = DataManager.Instance.player

        if (this.x === playerX && this.y === playerY && this.state === ENTITY_STATE_ENUM.IDLE) {
            this.state = ENTITY_STATE_ENUM.ATTACK
        } else if (this.state === ENTITY_STATE_ENUM.ATTACK) {
            this.state = ENTITY_STATE_ENUM.DEATH
            //震动
            EventManager.Instance.emit(EVENT_ENUM.SCREEN_SHAKE, SHAKE_DIRECTION_ENUM.BOTTOM)
            if (this.x === playerX && this.y === playerY) {
                //发送通知玩家死亡
                EventManager.Instance.emit(EVENT_ENUM.ATTACK_PLAYER, ENTITY_STATE_ENUM.AIR_DEATH)
            }
        }
    }
}

